package com.smh.yunpicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.smh.yunpicturebackend.exception.BusinessException;
import com.smh.yunpicturebackend.exception.ErrorCode;
import com.smh.yunpicturebackend.pojo.constant.FileConstant;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author shiminghui
 * @date 2025/6/21 00:00
 * @description: Multipart 文件上传
 */
@Component
public class PictureUpload extends PictureUploadTemplate {
    @Override
    protected void validPicture(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;

        // 校验文件大小
        long fileSize = multipartFile.getSize();
        if (fileSize > FileConstant.MAX_IMAGE_SIZE) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小超出限制");
        }

        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        // 获取文件后缀
        String fileSuffix = FileUtil.getSuffix(fileName);
        // 判断文件后缀是否为图片格式
        if (!FileConstant.IMAGE_SUFFIX_LIST.contains(fileSuffix)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件格式错误");
        }
    }

    @Override
    protected File createTempFile(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;

        try {
            File tempFile = File.createTempFile(FileConstant.TEMP_FILE_PREFIX + IdUtil.simpleUUID(), null);
            // 将MultipartFile转换为File
            multipartFile.transferTo(tempFile);

            return tempFile;
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "创建临时文件失败");
        }
    }

    @Override
    protected String getFileName(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }
}
